<template>
  <transition name="el-zoom-in-center">
    <div class="jsbos-preview-main">
      <div class="jsbos-common-page-header">
        <el-page-header
          @back="goBack"
          :content="!dataForm.id ? '新建' : '编辑'"
        />
        <div class="options">
          <el-button
            :loading="btnLoading"
            type="primary"
            @click="dataFormSubmit()"
          >
            保 存</el-button
          >
          <el-button @click="goBack"> 取 消</el-button>
        </div>
      </div>
      <el-row
        :gutter="15"
        class="main"
        :style="{ margin: '0 auto', width: '100%' }"
      >
        <el-form
          ref="elForm"
          :model="dataForm"
          :rules="rules"
          size="small"
          label-width="100px"
          label-position="right"
        >
          <template v-if="!loading">
            <el-col :xs="24" :md="12" :lg="8" :xl="6">
              <el-form-item label="试卷目录" prop="categoryId">
                <tree-select
                  ref="categoryTreeSelectRef"
                  v-model="dataForm.categoryId"
                  :options="categoryIdOptions"
                  :props="categoryIdProps"
                  :style="{ width: '100%' }"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12" :lg="8" :xl="6">
              <el-form-item label="试卷名称" prop="fullName">
                <el-input
                  v-model="dataForm.fullName"
                  placeholder="请输入"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12" :lg="8" :xl="6">
              <el-form-item label="版本" prop="paperrandomVersion">
                <span slot="label">
                  <el-tooltip
                    content="同一场考试中，所有学员参与考试使用的试卷是否同一版本"
                    placement="top"
                  >
                    <i
                      class="icon-ym icon-ym-header-about"
                      style="font-size: 14px"
                    ></i>
                  </el-tooltip>
                  版本
                </span>
                <el-radio-group
                  v-model="dataForm.paperrandomVersion"
                  size="small"
                >
                  <el-radio
                    v-for="(item, index) in paperrandomVersionOptions"
                    :key="index"
                    :label="item.id"
                    :disabled="item.disabled"
                  >
                    {{ item.fullName }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="试卷介绍" prop="intro">
                <el-input
                  v-model="dataForm.intro"
                  placeholder="请输入"
                  :maxlength="500"
                  :style="{ width: '100%' }"
                  true
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 4 }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="按等级组卷" prop="openDifficultyGrade">
                <el-switch
                  v-model="dataForm.openDifficultyGrade"
                  :active-value="1"
                  :inactive-value="0"
                  @change="initSettingSorce"
                >
                </el-switch>
                <span style="margin-left: 10px">是否按试题等级组卷</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <FormRandomGradeNo
                v-if="formRandomGradeNoVisible"
                ref="FormRandomGradeNoRef"
                :dataFormRandom="dataForm"
                :gradeRules="gradeNoRules"
              >
              </FormRandomGradeNo>
              <FormRandomGradeYes
                v-if="formRandomGradeYesVisible"
                ref="FormRandomGradeYesRef"
                :dataFormRandom="dataForm"
                :difficultyGradeOptions="difficultyGradeOptions"
                :gradeRules="gradeYesRules"
              >
              </FormRandomGradeYes>
            </el-col>
          </template>
        </el-form>
      </el-row>
      <QuestionLibDialog
        ref="questionLibRef"
        v-if="questionLibVisible"
        :folders="dataForm.folders"
        @table-change="selectQuestionLibChange"
      >
      </QuestionLibDialog>
    </div>
  </transition>
</template>
<script>
import { getInfo, Update, Create } from "@/views/exam/api/paper";
import { getSelector as getGradeSelector } from "@/views/exam/api/difficultyGrade";
import QuestionLibDialog from "@/views/exam/paper/questionLibDialog.vue";
import FormRandomGradeNo from "@/views/exam/paper/FormRandomGradeNo.vue";
import FormRandomGradeYes from "@/views/exam/paper/FormRandomGradeYes.vue";

export default {
  components: { QuestionLibDialog, FormRandomGradeNo, FormRandomGradeYes },
  props: {
    categoryIdOptions: {
      type: Array,
      default: [],
    },
    categoryIdProps: {
      type: Object,
      default: {
        children: "children",
        label: "fullName",
        value: "id",
      },
    },
  },
  data() {
    return {
      visible: false,
      questionLibVisible: false,
      formRandomGradeNoVisible: false,
      formRandomGradeYesVisible: false,
      loading: false,
      btnLoading: false,
      paperType: "2", // 1-固定版本 2-随机版本
      gradeNoRules: [],
      gradeYesRules: [],
      dataForm: {
        categoryId: "",
        enCode: "",
        fullName: "",
        intro: "",
        paperrandomVersion: "2",
        openDifficultyGrade: 0,
        folders: [],
        folderList: [],
        passLine: 60,
        myScore: 0,
        passScore: 0,
        description: "",
        enabledMark: 1,
        rules: [],
        questions: [],
      },
      rules: {
        categoryId: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],
        enCode: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        fullName: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        passLine: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
      },
      paperrandomVersionOptions: [
        { fullName: "固定版本", id: "1" },
        { fullName: "随机版本", id: "2" },
      ],

      questionTypeOptions: [],
      difficultyGradeIdOptions: [],
      scoreTypeOptions: [
        { fullName: "空", id: "1" },
        { fullName: "题", id: "2" },
      ],
      subQuestionScoreRuleOptions: [
        { fullName: "整题", id: "1" },
        { fullName: "每小题", id: "2" },
      ],
      difficultyGradeOptions: [],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getquestionTypeOptions();
    this.getDifficultyGradeOptions();
  },
  mounted() {},
  methods: {
    temsexampaperruleExist() {
      let isOk = true;
      for (let i = 0; i < this.dataForm.rules.length; i++) {
        const e = this.dataForm.rules[i];
      }
      return isOk;
    },
    /**
     * 获取试题等级 下拉选择项
     */
    getDifficultyGradeOptions() {
      getGradeSelector()
        .then((res) => {
          this.difficultyGradeOptions = res.data;
        })
        .catch(() => {
          this.difficultyGradeOptions = [];
        });
    },
    getquestionTypeOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "questionType",
        })
        .then((res) => {
          this.questionTypeOptions = res;
        });
    },
    goBack() {
      this.$emit("refresh", this.paperType);
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
    },
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          getInfo(this.dataForm.id).then((res) => {
            this.dataInfo(res.data);
            this.initSettingSorce();
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.passLine = 60;
          this.dataForm.paperrandomVersion = "2";
          this.dataForm.openDifficultyGrade = 0;
          this.dataForm.enabledMark = 1;
          this.initSettingSorce();
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      // 转换 paperRules
      let _paperRules = this.paperRules();
      this.dataForm.rules = _paperRules;
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if (!this.temsexampaperruleExist()) return;
          var _data = this.dataList();
          console.log("----", _data);
          this.btnLoading = true;
          const formMethod = this.dataForm.id ? Update : Create;
          formMethod(_data)
            .then((res) => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refresh", true);
                },
              });
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    initSettingSorce() {
      this.formRandomGradeNoVisible = false;
      this.formRandomGradeYesVisible = false;
      if (!this.dataForm.id) {
        this.dataForm.folders = [];
        this.dataForm.folderList = [];
      }
      // 初始化 设置评分规则得表单
      if (this.dataForm.openDifficultyGrade == 0) {
        this.formRandomGradeNoVisible = true;
        this.$nextTick(() => {
          this.$refs.FormRandomGradeNoRef.init();
        });
      } else {
        this.formRandomGradeYesVisible = true;
        this.$nextTick(() => {
          this.$refs.FormRandomGradeYesRef.init();
        });
      }
    },
    paperRules() {
      if (this.dataForm.openDifficultyGrade == 0) {
        return this.$refs.FormRandomGradeNoRef.getPaperRules();
      } else {
        return this.$refs.FormRandomGradeYesRef.getPaperRules();
      }
    },
    addRules() {
      let item = {
        paperId: undefined,
        folderId: undefined,
        questionType: undefined,
        difficultyGradeId: undefined,
        questionNum: undefined,
        score: undefined,
        missedScore: undefined,
      };
      this.dataForm.rules.push(item);
    },
    delRules(index) {
      this.dataForm.rules.splice(index, 1);
    },
    // 计算 总分
    sumTotalScore() {
      let _totalScore = 0;
      this.dataForm.questions.forEach((item) => {
        item.score = item.score ? item.score : 0;
        _totalScore += item.score;
      });
      this.dataForm.myScore = _totalScore;
      this.sumPassScore();
    },
    // 计算 及格线
    sumPassScore() {
      let _passLine = this.dataForm.passLine;
      this.dataForm.passLine = _passLine ? _passLine : 0;
      _passLine = new Number(this.dataForm.passLine);
      let _totalScore = this.dataForm.myScore;
      this.dataForm.myScore = _totalScore ? _totalScore : 0;
      _totalScore = new Number(this.dataForm.myScore);
      this.dataForm.passScore = Math.round((_passLine * _totalScore) / 100);
      this.$forceUpdate();
    },
    // 添加试题库 弹框
    addQuestionLibs() {
      this.questionLibVisible = true;
      this.$nextTick(() => {
        this.$refs.questionLibRef.initData();
      });
    },
    // 选中试题库 change事件
    selectQuestionLibChange(multipleSelection) {
      console.log("multipleSelection", multipleSelection);
      if (multipleSelection) {
        let _folders = [];
        let _paperFolderList = [];
        multipleSelection.forEach((item) => {
          let _questionLib = {
            paperId: undefined,
            questionLibId: item.id,
            questionLibName: item.fullName,
            selectTi: item.questions.selectTi ? item.questions.selectTi : 0,
            multiple: item.questions.multiple ? item.questions.multiple : 0,
            determine: item.questions.determine ? item.questions.determine : 0,
            blank: item.questions.blank ? item.questions.blank : 0,
            answers: item.questions.answers ? item.questions.answers : 0,
            cases: item.questions.cases ? item.questions.cases : 0,
          };
          _paperFolderList.push(_questionLib);
          _folders.push(item.id);
        });
        this.dataForm.folderList = _paperFolderList;
        this.dataForm.folders = _folders;
      } else {
        this.dataForm.folderList = [];
        this.dataForm.folders = [];
      }
      this.questionLibVisible = false;
    },
    //删除试题库
    delQuestionLibs(index) {
      this.dataForm.folders.splice(index, 1);
      this.dataForm.folderList.splice(index, 1);
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      _data.openDifficultyGrade = parseInt(_data.openDifficultyGrade);
      _data.enabledMark = parseInt(_data.enabledMark);
      _data.openDifficultyGrade = parseInt(_data.openDifficultyGrade);
      for (let i = 0; i < _data.rules.length; i++) {
        var _list = _data.rules[i];
      }
      for (let i = 0; i < _data.folderList.length; i++) {
        var _list = _data.folderList[i];
      }
      _data.folders = JSON.stringify(_data.folders);
      _data.paperType = this.paperType;
      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      _dataAll.openDifficultyGrade = parseInt(_dataAll.openDifficultyGrade);
      _dataAll.enabledMark = parseInt(_dataAll.enabledMark);
      for (let i = 0; i < _dataAll.rules.length; i++) {
        var _list = _dataAll.rules[i];
      }
      for (let i = 0; i < _dataAll.folderList.length; i++) {
        var _list = _dataAll.folderList[i];
      }
      _dataAll.folders = JSON.parse(_dataAll.folders);
      if (_dataAll.openDifficultyGrade == 0) {
        this.gradeNoRules = _dataAll.rules;
      }
      if (_dataAll.openDifficultyGrade == 1) {
        this.gradeYesRules = _dataAll.rules;
      }
      this.dataForm = _dataAll;
    },
  },
};
</script>
